package com.net.retrofits.manager;


import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.hos.utile.DLog;
import com.hos.utile.Md5Utile;
import com.net.retrofits.common.BaseNetSource;
import com.net.retrofits.common.RequestBack;
import com.net.retrofits.data.UrlManger;
import com.net.retrofits.use.req.UseBaseReq;

import java.io.IOException;
import java.util.HashMap;
import java.util.Random;

import retrofit2.Retrofit;

/**
 * @author javacoder
 * @date 2016/10/19
 */

public abstract class BaseAbstractManager extends BaseManager {
    //已经退出登录(在别的手机上登录了)
    public static final int WHAT_LOCALITY_LOGIN_OUT = -1302;

    public BaseAbstractManager(RequestBack requestBack) {
        super(requestBack);
        init();
    }


    protected UseBaseReq baseReq;

    protected void setBaseReq(UseBaseReq baseReq) {
        this.baseReq = baseReq;
    }

    public void doRequest() {
        doRequest("");
    }


    public void doRequest(String other) {
        if (baseReq != null) {
            baseReq.setRandom(getRandom());
        }
        BaseNetSource source = new BaseNetSource();

        Retrofit retrofit = source.getRetrofit(new UrlManger());
        request(retrofit, other);
    }

    //获取随机码
    public static String getRandom() {
        Random random = new Random();
        String randoms = "";
        for (int i = 0; i < 4; i++) {
            int randomInt = random.nextInt(9);
            randoms += randomInt;
        }
        return randoms;
    }

    protected HashMap getHeadMap() {
        HashMap<String, String> map = new HashMap();
        String p = Md5Utile.encode("aAr9MVS9j1");
        String sign = Md5Utile.encode(p + obj2Json(baseReq));
        map.put("sign", sign);
//        map.put("sign", "test");
        DLog.e("过滤前sign_" + "sign:" + sign);
        return map;
    }


    private String obj2Json(Object obj) {
        if (obj == null) {
            return null;
        }
        String json = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            SimpleModule module = new SimpleModule();
            mapper.registerModule(module);
            // 过滤对象的null属性.
            mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
//            DLog.e("过滤前的obj" + obj.toString());
            json = mapper.writeValueAsString(obj);
//            DLog.e("过滤前的json" + json);
        } catch (JsonGenerationException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }

    protected abstract void init();

    protected abstract void request(Retrofit retrofit, String other);

}
